package cn.itcast.bos.web.action.base;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.StandardService;


@Actions
@Namespace("/")
@ParentPackage("struts-default")

@Controller
@Scope("prototype")
public class StandardAction extends ActionSupport implements ModelDriven<Standard>{
	
	@Autowired
	private StandardService service;
	
	private Standard s = new Standard();
	
	@Override
	public Standard getModel() {
		return s;
	}
	
	//转发地址栏路径没改变，html中使用相对路径无法加载到js和css
	@Action(value="standard_save",results={@Result(name="success",type="redirect",location="/pages/base/standard.html")})
	public String save() {
		service.save(s);
		return SUCCESS;
	}
	
	//属性驱动
	private int page;
	private int rows;

	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	//分页列表查询
	@Action(value="standard_pageQuery")
	public void pageQuery(){
//		long count = s.findTotal();
		Pageable pageable = new PageRequest(page - 1, rows);
		Page<Standard> pageData = service.findPageData(pageable);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("total", pageData.getTotalPages());
		result.put("rows", pageData.getContent());
		String jsonString = JSONObject.toJSONString(result);
		System.out.println(jsonString);
		try {
			ServletActionContext.getResponse().setCharacterEncoding("utf-8");
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	//查询所有
	@Action(value="standard_findAll")
	public void findAll(){
//			long count = s.findTotal();
		
		List<Standard> list = service.findAll();
		String jsonString = JSONObject.toJSONString(list);
		System.out.println(jsonString);
		try {
			ServletActionContext.getResponse().setCharacterEncoding("utf-8");
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
